package com.xiaobai.servlet.user;

import com.xiaobai.pojo.User;
import com.xiaobai.service.user.UserServiceImpl;
import com.xiaobai.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @Author 小白学CS
 * @Version 1.0
 */
public class LoginServlet extends HttpServlet {


    //Servlet：控制层调取业务层

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        System.out.println("login servlet——start——");
        //获取用户名和密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        //和数据库中的账号和密码对比，调用业务层
        UserServiceImpl userService = new UserServiceImpl();
        //这里就可以把登录者在数据库中查询出来了
        User user = null;
        try {
            user = userService.login(userCode, userPassword);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        //如果用户不为空，即可登录
        if (user != null) {
            req.getSession().setAttribute(Constants.USER_SERSSION, user);
            //跳转主页
            resp.sendRedirect("/jsp/frame.jsp");
        }else {//无法登录，转发会登陆页面，并提示用户名或者密码错误
            req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
            req.setAttribute("error", "用户名或者密码错误");
        }
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
